package com.chen.shopping_order_customer_api.controller;

import com.alibaba.fastjson2.JSON;
import com.chen.shopping_common.pojo.Orders;
import com.chen.shopping_common.pojo.Payment;
import com.chen.shopping_common.result.BaseResult;
import com.chen.shopping_common.service.OrderService;
import com.chen.shopping_common.service.PayService;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.json.Json;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/payment")
public class PaymentController {

    @DubboReference
    private PayService payService;
    @DubboReference
    private OrderService orderService;



    /**
     * 生成二维码
     * @param orderId 订单id
     * @return 二维码字符串
     */
    @PostMapping("/pcPay")
    public BaseResult<String> pcPay(String orderId){
        Orders orders = orderService.findById(orderId);
        String s = payService.pcPay(orders);
        return BaseResult.ok(s);
    }

    /**
     * 支付回调方法：该方法由支付宝调用
     * @param request
     * @return
     */
    @PostMapping("/success/notify")
    @GlobalTransactional
    public BaseResult successNotify(HttpServletRequest request){
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String,String[]> newMap = new HashMap<>();
        newMap.putAll(parameterMap);
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("requestParameterMap",newMap);
        //验签
        payService.checkSign(paramMap);
        String tradeStatus = request.getParameter("trade_status"); //订单状态
        String outTradeNo = request.getParameter("out_trade_no"); //订单编号
        if (tradeStatus.equals("TRADE_SUCCESS")){
            Orders orders = orderService.findById(outTradeNo);
            orders.setStatus(2);  //设置订单状态
            orders.setPaymentTime(new Date()); //设置支付时间
            orders.setPaymentType(2); //设置支付渠道
            orderService.update(orders);

            int i = 1/0;
            //封装交易信息
            Payment payment = new Payment();
            payment.setOrderId(outTradeNo); //订单编号
            payment.setTransactionId(outTradeNo); //交易号
            payment.setTradeType("支付宝支付"); //交易类型
            payment.setTradeState(tradeStatus); //交易状态
            payment.setPayerTotal(orders.getPayment()); //支付金额
            payment.setContent(JSON.toJSONString(request.getParameterMap())); //支付详情
            payment.setCreateTime(new Date()); //支付时间
            payService.addPayment(payment); //向数据库中保存支付数据
        }

        return BaseResult.ok();
    }
}
